import axios from 'axios'
import router from '@/router'
import store from '@/store'
import config from '@/configure'
import encryptTool from '@/utils/encryptTool'
import vm from '@/main'
import errCode from './err-code'

const isEncrypted = config.isEncrypted && config.encryptType === 'AES'
const AESkey = encryptTool.getRandomKey()

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'

/* eslint class-methods-use-this: 0 */
/* eslint no-param-reassign: 0 */
/* eslint no-underscore-dangle: 0 */
export default class Server {
  axios (method, url, params) {
    return new Promise((resolve, reject) => {
      let _option = {
        method,
        url,
        data: null,
        params: null,
        headers: null,
        timeout: 10 * 1000,
        responseType: null
        // withCredentials: true
      }
      typeof params !== 'object' && (params = {})
      !params.headers && (params.headers = {})
      params.headers['Csrf-Token'] = store.getters.token
      let encrypt = isEncrypted && (!params.data || Object.prototype.toString.call(params.data) === '[object Object]' || Object.prototype.toString.call(params.data) === '[object Array]')
      isEncrypted && (params.headers['Cipher-Key'] = encryptTool.RSAencrypt(AESkey))
      encrypt && params.data && (params.data = encryptTool.AESencrypt(JSON.stringify(params.data), AESkey))
      encrypt && !params.headers['content-type'] && (params.headers['content-type'] = 'application/json;charset=UTF-8')
      Object.assign(_option, params)

      axios.request(_option).then(res => {
        res.data && isEncrypted && res.headers['content-type'] && res.headers['content-type'].indexOf('application/json') !== -1 && (res.data = encryptTool.AESdecrypt(res.data, AESkey))
        res.data && res.headers['content-type'] && res.headers['content-type'].indexOf('application/json') !== -1 && (res.data = typeof res.data === 'object' ? res.data : JSON.parse(res.data))
        res.data && !res.data.success && vm.$notifyBox(errCode[res.data.code] || res.data.msg, 'error')
        resolve(typeof res.data === 'object' ? res.data : JSON.parse(res.data))
      }).catch(err => {
        if (err.response && err.response.status === 401) {
          vm.$notifyBox('登录超时，请重新登录')
          router.push({ name: 'login' })
          return
        }
        if (err.response && err.response.status === 403) {
          router.push({ name: 'err403' })
          return
        }
        vm.$notifyBox(vm.GLOBAL.MSG.CATCH_MSG)
        window.console && console.log(err)
        if (err.response) {
          reject(err.response.data)
          return
        }
        reject(err)
      })
    })
  }
}
